package com.idc.resource.util;


import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.MDC;

import java.util.UUID;

/**
 * log日志辅助类
 * Created by Lijing on 2016/11/11.
 */
public class LogUtil {

    private static final String LOG_UUID = "LOG_UUID";

    private static final String LOG_TOKEN = "LOG_TOKEN";

    private static final String LOG_USER_ID = "LOG_USER_ID";


    /**
     * 更新日志跟踪id
     * @param logID 日志跟踪id(为空时创建新日志跟踪id)
     */
    public static void  updateLogId(String logID){
        if(StringUtils.isBlank(logID)){
            MDC.put(LOG_UUID,createLogId());
        }else {
            MDC.put(LOG_UUID, logID);
        }
    }

    /**
     * 更新用户登录信息
     * @param userId 用户id
     * @param token 用户登录令牌
     */
    public static void  updateUserInfo(String userId,String token){
        if(!StringUtils.isBlank(userId)){
            MDC.put(LOG_USER_ID, userId);
        }
        if(!StringUtils.isBlank(token)){
            MDC.put(LOG_TOKEN, token);
        }
    }

    /**
     * 创建日志跟踪id
     * @return 日志跟踪id
     */
    public static String createLogId(){
        return UUID.randomUUID().toString();
    }

    /**
     * 获取日志跟踪id
     * @return 日志跟踪id
     */
    public static String getLogId(){
        Object object =  MDC.get(LOG_UUID);
        if(object==null){
            return null;
        }else {
            return object.toString();
        }
    }

    /**
     * 获取登录用户id
     * @return 登录用户id
     */
    public static String getUserId(){
        Object object =  MDC.get(LOG_USER_ID);
        if(object==null){
            return null;
        }else {
            return object.toString();
        }
    }

    /**
     * 获取登录令牌信息
     * @return 令牌信息
     */
    public static String getLogToken(){
        Object object =  MDC.get(LOG_TOKEN);
        if(object==null){
            return null;
        }else {
            return object.toString();
        }
    }
}
